<?php
/**
 * Elgg long text input
 * Displays a long text input field that can use WYSIWYG editor
 *
 * @package Elgg
 * @subpackage Core
 *
 * @uses $vars['value']    The current value, if any - will be html encoded
 * @uses $vars['disabled'] Is the input field disabled?
 * @uses $vars['class']    Additional CSS class
 */

$name = $vars['name'];
$form_id = $vars['form_id'];
$readonly = $vars['readonly'];

if (isset($vars['class'])) {
	$vars['class'] = "elgg-input-blog {$vars['class']}";
} else {
	$vars['class'] = "elgg-input-blog";
}

$defaults = array(
	'value' => '',
	'id' => 'elgg-input-' . rand(), //@todo make this more robust
);

$vars = array_merge($defaults, $vars);

$value = $vars['value'];
unset($vars['value']);

if (!$readonly) {
echo elgg_view_menu('blogpicker', array(
	'sort_by' => 'priority',
	'class' => 'elgg-menu-hz',
	'id' => $vars['id'],
));
}

//echo 'value:';
//print_r($value);
?>

<ul <?php echo elgg_format_attributes($vars);  ?> style='height:100px;'>
<?php 
if (!$readonly) {
	$close_btn = "&nbsp;&nbsp;&nbsp;<a class='delblog' href='#'>x</a>";
}
if (is_array($value)) {
	foreach ($value as $blog) {
		$blog_entity = get_entity($blog);
		$blog_url = $blog_entity->getURL();
		echo "<li id='$blog'><a href='$blog_url' target='_blank'>$blog_entity->title</a>$close_btn</li>";
	}
} else if($value) {
	$blog = $value;
		$blog_entity = get_entity($blog);
		if($blog_entity) {
			$blog_url = $blog_entity->getURL();
			echo "<li id='$blog'><a href='$blog_url' target='_blank'>$blog_entity->title</a>$close_btn</li>";
		}
} else {}

?>
</ul>
<script>
$(document).ready(function(){
<?php
if (!$readonly) {
?>
	$("form#<?php echo $form_id; ?>").submit(function(){
		//console.log('submit');
		var form_obj = $(this);
		$(this).find(".elgg-input-blog li").each(function(){
			var blog_id = $(this).attr("id");
			//console.log('each'+form_obj.attr("id"));
			if (blog_id) {
				console.log(blog_id);
				form_obj.append("<input type='hidden' name='blogs[]' value='"+blog_id+"'>");
			}
		});
		//return false;
	});
	
	$(".delblog").live("click", function(){
		$(this).parent("li").remove();
	});
<?php
}
?>
});
</script>
